package com.kob.backend.service;

import jakarta.annotation.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URL;
import java.util.Map;

/**
 * <pre>{@code
 *
 * }</pre>
 *
 * @author Summerday
 * @date 2023/3/21
 */
@Service
public class HTTPService {
    @Resource
    private RestTemplate restTemplate;

    public void doGET(URL url, Map<String, String> params) {
        // 构建带参数的URL
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url.toString());
        params.forEach(builder::queryParam);

        // 发送GET请求
        String result = restTemplate.getForObject(builder.toUriString(), String.class);
        System.out.println(result);
    }

    public String doPOST(URL url, Map<String, String> body) {
        // 设置请求头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 设置请求体
        HttpEntity<Map<String, String>> request = new HttpEntity<>(body, headers);

        // 发送POST请求
        String result = restTemplate.postForObject(url.toString(), request, String.class);
        System.out.println(result);
        return result;
    }
}
